package epam.marchenko.library.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import epam.marchenko.library.domain.Book;
import epam.marchenko.library.domain.BookClass;

@Repository(value="bookRepository")
public class BookRepositoryJpaImpl implements BookRepository {
	@PersistenceContext
	private EntityManager em;

	public BookRepositoryJpaImpl() {}

	public BookRepositoryJpaImpl(EntityManager em) {
		this.em = em;
	}

	public Book findById(int id) {
		return em.find(Book.class, id);
	}

	public Book find(Book book) {
		return em.find(Book.class, book.getId());
	}

	public List<Book> findAll() {
		TypedQuery<Book> query = em.createNamedQuery("Book.findAll",
				Book.class);
		return query.getResultList(); 
	}

	@Transactional
	public void create(Book book) {
		  em.persist(book);
	}

	@Transactional
	public void delete(Book book) {
			  em.remove(findById(book.getId()));
	}

	@Transactional
	public void deleteById(int id) {
			  em.remove(findById(id));
	}

	@Transactional
	public void update(Book book) {
			  em.merge(book);
	}

	public List<Book> findAllForClass(BookClass bclass) {
		TypedQuery<Book> query = em.createNamedQuery("Book.findAllForClass",
				Book.class);
		query.setParameter("bclass", bclass);
		return query.getResultList(); 
	}

}
